import axios             from 'axios'
import Vue               from 'vue'
import { BigNumber }     from 'bignumber.js'
import { Toast,Dialog }  from 'vant'
import CryptoJS          from 'crypto-js/crypto-js'
import md5               from 'js-md5'

Vue.use(Toast, Dialog)

axios.defaults.timeout = 10 * 1000;
axios.interceptors.request.use(
    config => {
        config.headers.lang     = readLang();
        config.headers.token    = getToken();
        config.headers.device   = '';
        config.headers.version  = getVersion();
        config.headers.platform = client() ? 'ios' : 'android';
        config.headers.country  = getCountry();
        return config
    },
    err => Promise.reject(err)
);

axios.interceptors.response.use(
    config => {
        return config
    },
    err => {
        //提交超时的情况
        if(JSON.stringify(err.message.includes('timeout'))){
            // throw new Error('timeout+"'+ err.config.url +'",uid:'+window.localStorage.getItem('uid'));
            console.log(err.config.url)
        }
    }
)

let status   = 4;               // 1:开发   2:测试   3:pre预生产   4:生产
let useCache = false;           // IOS包是否支持缓存
let debug    = false;           // 是否本地调试
let ajaxUrl  = status == 1 ? 'https://dev-mapi.deepcoin.me' : status == 2 ? 'https://uat-mapi.deepcoin.me' : status == 3 ? 'https://pre-mapi.deepcoin.me' : 'https://net-mapi.deepcoin.art';
let ajaxUrl2 = status == 1 ? 'https://dev-agent.deepcoin.me' : status == 2 ? 'https://uat-agent.deepcoin.me' : status == 3 ? 'https://pre-agent.deepcoin.me' : 'https://net-agent.cheboss.com.cn';
let ajaxUrl3 = status == 1 ? 'https://dev-wapi.deepcoin.me' : status == 2 ? 'https://uat-wapi.deepcoin.me' : status == 3 ? 'https://pre-wapi.deepcoin.me' : 'https://net-wapi.cheboss.com.cn';
let ajaxUrl4 = status == 1 ? 'https://dev-api.deepcoin.me' : status == 2 ? 'https://uat-api.deepcoin.me' : status == 3 ? 'https://pre-api.deepcoin.me' : 'https://net-api.cheboss.com.cn';
let wssUrl   = status == 1 ? 'wss://dev-redws.deepcoin.pro/redpkg' : status == 2 ? 'wss://uat-redws.deepcoin.pro/redpkg' : status == 3 ? 'wss://pre-redws.deepcoin.pro/redpkg' : 'wss://net-redws.deepcoin.pro/redpkg';
let time     = 10000;           //重复获取实时价格时间配置

//判断是否嵌入bbj app中
let inBBJ = () => {
    // return true
    return window.navigator.userAgent.indexOf('3RAPP') > -1
}

//判断是否iphone x
let isIphoneX = () => {
    if (
        /(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent) &&
        /(375|414|390|428)/i.test(screen.width) &&
        /(812|896|844|926)/i.test(screen.height)
    ) {
        return true;
    } else {
        return false;
    }
}

/**
 * 尼日利亚对应名称
 */
const Nigeria = {
    name: 'NGN',
    abbr: 'N',
    icon: 'https://n-bkt.deepcoin.me/USDT.png'
}

//设置cookie
let setCookie = (name, value) => {
    //读取主域名
    var hostArr = window.location.host.split('.');
    hostArr[0] = '';
    let domain = hostArr.join('.');
    //设置cookie
    var Days = 30;
    var exp = new Date()
    exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000)
    document.cookie =
        name +
        '=' +
        escape(value) +
        ';expires=' +
        exp.toGMTString() +
        ';path=/;domain='+ domain +';'
}

//读取cookie
let getCookie = name => {
    var arr, reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)');
    if ((arr = document.cookie.match(reg))) {
        return unescape(arr[2])
    } else {
        return null
    }
}

//删除cookie
let delCookie = name => {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = getCookie(name);
    if (cval != null) document.cookie = name + '=' + cval + ';expires=' + exp.toGMTString()
}

//获取版本号
let getVersion = () => {
    return getCookie('version') || ''
}

//获取设备信息
let getDevice = () => {
    return getCookie('device') || ''
}

//获取所在国家
let getCountry = () => {
    return getCookie('country') || ''
}

//返回token
let getToken = () => {
    if (debug) return getStorage('token');
    // let _token = getStorage('token');
    return window.token || getCookie('localToken') || getStorage('token') || ''
}

let waitSDKReady = _from => {
    return new Promise((resolve, reject) => {
        if (debug) {
            //浏览器调试开发模式
            resolve(getStorage('token'));
            return
        }
        //在bbj中
        let times = 0;
        function getT () {
            times++;
            let token = window.token || getCookie('localToken') || getStorage('token') || ''
            if (token) {
                resolve(token)
                setStorage('token', token)
                return
            }
            if (times < 10) {
                setTimeout(() => {
                    getT()
                },200)
                return
            } else {
                reject()
            }
        }
        getT()
    })
}

let fetch = (_url, datas) => {
    return new Promise((resolve, reject) => {
        // if (client() && inBBJ() && useCache) {
        //     //IOS in BBJ
        //     datas.convertPOST = 1;
        //     axios.get(_url, { params: datas }).then(res => {
        //         if (res.status === 200) {
        //             resolve(res.data,datas)
        //             if (res.data.retCode === 100002 || res.data.retCode === 1000010) {
        //                 //token过期情况处理
        //                 if (inBBJ()) {
        //                     window.token = '';
        //                     localStorage.removeItem('token');
        //                     delCookie('localToken');
        //                     setTimeout(() => {
        //                         callHandler('showLogin', {}, res => {
        //                             console.log(res)
        //                         })
        //                     }, 500)
        //                 } else {
        //                     // alert('登录超时，请退出重新进入')
        //                 }
        //             }
        //         } else {
        //             reject(res)
        //             Toast('服务器错误')
        //         }
        //     }).catch(res => {
        //         reject('');
        //         // Toast('网络繁忙，请稍后再试')
        //         console.log(res)
        //     })
        // } else {
            axios.post(_url, datas).then(res => {
                // console.log(res)
                if (res.status === 200) {
                    if (res.data.retCode == 100002 || res.data.retCode === 1000010) {
                        //token过期情况处理
                        window.token = '';
                        window.localStorage.clear();
                        delCookie('localToken');
                        setTimeout(() => {
                            callHandler('showLogin', {}, res => {
                                console.log(res)
                            })
                        }, 500)
                    }
                    resolve(res.data,datas)
                } else {
                    reject(res)
                    Toast('服务器错误')
                }
            }).catch(res => {
                reject('');
                console.log(res)
                // console.log(JSON.stringify(res))
                // Toast('网络繁忙，请稍后再试')
            })
        // }
    })
}


let fetch2 = (_url, datas) => {
    return new Promise((resolve, reject) => {
        axios.get(_url, { params: datas }, { headers: { lang: readLang() } }).then(res => {
            if (res.status === 200) {
                resolve(res.data,datas);
                if (res.data.retCode === 100002 || res.data.retCode === 1000010) {
                    window.token = '';
                    localStorage.removeItem('token');
                    delCookie('localToken');
                    callHandler('showLogin', {}, res => {
                        console.log(res)
                    })
                    //token过期情况处理
                    // if(inBBJ() && window.location.hash.indexOf('my') == -1){
                    //     window.token = '';
                    //     localStorage.removeItem('token');
                    //     window.location.reload();
                    // }else{
                    //     // alert('登录超时，请退出重新进入')
                    // }
                }
            } else {
                reject(res)
                Toast('服务器错误')
            }
        }).catch(res => {
            reject('');
            // Toast('网络繁忙，请稍后再试')
            console.log(res)
        })
    })
}

let getQueryString = function (name) {
    if (!name) return null
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search == "" ? null : decodeURIComponent(window.location.search).substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null
}

//判断客户端为安卓还是IOS
let client = () => /(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent) ? true : false

let digitLength = (num) => {
    if (!num) return 0
    const eSplit = num.toString().split(/[eE]/);
    const len = (eSplit[0].split('.')[1] || '').length - (+(eSplit[1] || 0));
    return len > 0 ? len : 0;
}

//精确加法
let accAdd = (num1, num2) => {
    const baseNum = Math.pow(10, Math.max(digitLength(num1), digitLength(num2)));
    return (accMul(num1, baseNum) + accMul(num2, baseNum)) / baseNum;
}

//精确减法
let subtr = (num1, num2) => {
    const baseNum = Math.pow(10, Math.max(digitLength(num1), digitLength(num2)));
    return (accMul(num1, baseNum) - accMul(num2, baseNum)) / baseNum;
}

//精确乘法
let accMul = (num1, num2) => {
    return Number(BigNumber(num1).multipliedBy(num2).toString())
    const num1Changed = num1 ? Number(num1.toString().replace('.', '')) : 0;
    const num2Changed = num2 ? Number(num2.toString().replace('.', '')) : 0;
    const baseNum = digitLength(num1) + digitLength(num2);
    return num1Changed * num2Changed / Math.pow(10, baseNum);
}

//精确相除
let accDiv = (num1, num2) => {
    return Number(BigNumber(num1).dividedBy(num2).toString())
    const num1Changed = num1 ? Number(num1.toString().replace('.', '')) : 0;
    const num2Changed = num2 ? Number(num2.toString().replace('.', '')) : 0;
    return accMul((num1Changed / num2Changed), Math.pow(10, digitLength(num2) - digitLength(num1)));
}

//设置本地缓存
let setStorage = (_key = 'bbj', _val) => {
    if (!_val) return
    if (typeof localStorage === 'object' && typeof localStorage.setItem === 'function') {
        localStorage.setItem(_key, typeof _val === 'object' ? JSON.stringify(_val) : _val)
    } else {
        Toast('手机不支持localStorage缓存')
    }
}
//设置本地缓存
let setStorage2 = (_key = 'bbj', _val) => {
    if (!_val) return
    if (typeof sessionStorage === 'object' && typeof sessionStorage.setItem === 'function') {
        sessionStorage.setItem(_key, typeof _val === 'object' ? JSON.stringify(_val) : _val)
    } else {
        Toast('手机不支持localStorage缓存')
    }
}
//读取本地缓存
let getStorage = _key => {
    if (typeof localStorage === 'object' && typeof localStorage.getItem === 'function') {
        return localStorage.getItem(_key)
    } else {
        Toast('手机不支持localStorage缓存');
    }
}

//读取本地缓存
let getStorage2 = _key => {
    if (typeof sessionStorage === 'object' && typeof sessionStorage.getItem === 'function') {
        return sessionStorage.getItem(_key)
    } else {
        Toast('手机不支持localStorage缓存');
    }
}

/**
 * 截取小数位
 * @param target 被截取对象
 * @param num    需要截取的小数位  
 */
let countNum = (target, num = 2) => {
    if (isNaN(Number(target))) return 0
    if (typeof target === 'number') target = target.toString();
    if (target && target.indexOf('.') > -1) {
        let arrNewVal = target.split('.');
        //若不足切割小数位，则强制保留对应位数
        if (arrNewVal[1].length <= num) {
            return Number(target).toFixed(num)
        }
        if (arrNewVal.length > 0 && arrNewVal[1].length > num) {
            arrNewVal[1] = arrNewVal[1].substr(0, num);
            target = arrNewVal.join('.');
        } else {
            return Number(target).toFixed(num)
        }
    } else {
        return Number(target).toFixed(num)
    }
    return target
}

//根据币种名称获取价格
let getPriceByName = (name, type, number, from) => {
    return new Promise((resolve, reject) => {
        fetch(`${ajaxUrl}/otc/price`, {
            token: getToken(),
            currency_id: name,
            type: type,
            number: +number || 1
        }).then(res => {
            if (res.retCode === 0) {
                if (from && from === 'index') {
                    resolve(res.retData)
                } else {
                    resolve(+res.retData.price)
                }
            } else {
                reject(res.retMsg || res.retData)
                Toast(res.retMsg || res.retData || '未知错误')
            }
        }).catch(error => {
            console.log(error)
        })
    })
}

//尼日利亚-充值-提现 汇率接口
let getCurrencyRate = (params) => {
    return new Promise((resolve, reject) => {
        fetch2(`${ajaxUrl}/nigeria/site/currency-rate`, params).then(res => {
            let { retCode = -1, retData } = res || {}
            if (retCode == 0) {
                resolve(res)
            } else {
                reject(res)
            }
        })
    })
}

let bridgeData = list => {
    //转换支付、付款格式
    return new Promise((resolve, reject) => {
        try {
            let _dot = process.env.NODE_ENV === 'development' ? '../../' : './';
            list.sort((a, b) => b.recommend - a.recommend);
            list.map(item => {
                item.isSelected = item.recommend == 1 ? true : false;
                if (item.type == 1) {
                    //支付宝
                    item.name = '支付宝';
                    item.icon = _dot + 'static/images/alipay.png';
                } else if (item.type == 2) {
                    //银行卡
                    item.name = '银行卡';
                    item.icon = _dot + 'static/images/bankCard.png';
                } else if (item.type == 3) {
                    //微信
                    item.name = '微信';
                    item.icon = _dot + 'static/images/weixin.png';
                }
            })
            resolve(list)
        } catch (e) {
            reject(e)
        }
    })
}


let transTime = (temp, tip) => {
    //确保时间戳为13位
    temp = temp.toString().length == 10 ? temp * 1000 : temp;
    temp = Number(temp);
    let _newDate = new Date(temp);
    let postYear = _newDate.getFullYear();
    let postMonth = _newDate.getMonth() + 1;
    let postDate = _newDate.getDate();
    let postHours = _newDate.getHours();
    let postMinutes = _newDate.getMinutes();
    let postMM = _newDate.getSeconds();
    postMonth = postMonth.toString().length === 1 ? '0' + postMonth : postMonth;
    postDate = postDate.toString().length === 1 ? '0' + postDate : postDate;
    postHours = postHours.toString().length === 1 ? '0' + postHours : postHours;
    postMinutes = postMinutes.toString().length === 1 ? '0' + postMinutes : postMinutes;
    postMM = postMM.toString().length === 1 ? '0' + postMM : postMM;
    let t = postMonth + '月' + postDate + '日 ' + postHours + ':' + postMinutes + ':' + postMM;
    return tip ? (postYear + '-' + postMonth + '-' + postDate + ' ' + postHours + ':' + postMinutes + ':' + postMM) : t
}


let transTime2 = temp => {
    //确保时间戳为13位
    temp = temp.toString().length == 10 ? temp * 1000 : temp;
    temp = Number(temp);
    let _newDate = new Date(temp);
    let postYear = _newDate.getFullYear();
    let postMonth = _newDate.getMonth() + 1;
    let postDate = _newDate.getDate();
    let postHours = _newDate.getHours();
    let postMinutes = _newDate.getMinutes();
    let postMM = _newDate.getSeconds();
    postMonth = postMonth.toString().length === 1 ? '0' + postMonth : postMonth;
    postDate = postDate.toString().length === 1 ? '0' + postDate : postDate;
    postHours = postHours.toString().length === 1 ? '0' + postHours : postHours;
    postMinutes = postMinutes.toString().length === 1 ? '0' + postMinutes : postMinutes;
    postMM = postMM.toString().length === 1 ? '0' + postMM : postMM;
    return postYear + '/' + postMonth + '/' + postDate + ' ' + postHours + ':' + postMinutes
}

let transTime3 = temp => {
    //确保时间戳为13位
    temp = temp.toString().length == 10 ? temp * 1000 : temp;
    temp = Number(temp);
    let _newDate = new Date(temp);
    let postYear = _newDate.getFullYear();
    let postMonth = _newDate.getMonth() + 1;
    let postDate = _newDate.getDate();
    let postHours = _newDate.getHours();
    let postMinutes = _newDate.getMinutes();
    let postMM = _newDate.getSeconds();
    postMonth = postMonth.toString().length === 1 ? '0' + postMonth : postMonth;
    postDate = postDate.toString().length === 1 ? '0' + postDate : postDate;
    postHours = postHours.toString().length === 1 ? '0' + postHours : postHours;
    postMinutes = postMinutes.toString().length === 1 ? '0' + postMinutes : postMinutes;
    postMM = postMM.toString().length === 1 ? '0' + postMM : postMM;
    return postMonth + '/' + postDate + ' ' + postHours + ':' + postMinutes
}

let transTime4 = temp => {
    //确保时间戳为13位
    temp = temp.toString().length == 10 ? temp * 1000 : temp;
    temp = Number(temp);
    let _newDate = new Date(temp);
    let postYear = _newDate.getFullYear();
    let postMonth = _newDate.getMonth() + 1;
    let postDate = _newDate.getDate();
    let postHours = _newDate.getHours();
    let postMinutes = _newDate.getMinutes();
    let postMM = _newDate.getSeconds();
    postMonth = postMonth.toString().length === 1 ? '0' + postMonth : postMonth;
    postDate = postDate.toString().length === 1 ? '0' + postDate : postDate;
    postHours = postHours.toString().length === 1 ? '0' + postHours : postHours;
    postMinutes = postMinutes.toString().length === 1 ? '0' + postMinutes : postMinutes;
    postMM = postMM.toString().length === 1 ? '0' + postMM : postMM;
    let arr = [];
    arr.push(postYear + '', postMonth + '', postDate + '', postHours + '', postMinutes + '', postMM + '')
    return arr
}

//字符串补全
const strPadStart = (str, num = 2, padS = '0') => {
    str = str.toString()
    return str.padStart(num, padS)
}

//返回天时分秒
let transTime5 = dateE => {
    let diff = parseInt(dateE)
    let diffD = Math.floor(diff / (24 * 3600 * 1000));  //相差天数
    let surplus1 = diff % (24 * 3600 * 1000)
    let diffH = Math.floor(surplus1 / (3600 * 1000))        //相差小时数
    let surplus2 = surplus1 % (3600 * 1000)
    let diffM = Math.floor(surplus2 / (60 * 1000))        //相差分钟数
    let surplus3 = surplus2 % (60 * 1000)
    let diffS = Math.round(surplus3 / 1000)              //相差秒数
    let str = ''
    str = diffD > 0 ? `${diffD}天` : ''
    str += diffH ? `${strPadStart(diffH)}:` : '00:'
    str += diffM ? `${strPadStart(diffM)}:` : '00:'
    str += diffS ? `${strPadStart(diffS)}` : '00'
    return str
}

// h5调用native方法
function callHandler (actionName, data, callback) {
    function getBridge () {
        if (window.bridge) {
            window.bridge.callHandler(actionName, data, function responseCallback (responseData) {
                var resObj = responseData;
                if (typeof responseData == 'string') {
                    try {
                        let jsonData = JSON.parse(responseData);
                        if (jsonData) {
                            resObj = jsonData;
                        }
                    } catch (e) {
                        console.log(e)
                        // Toast(e)
                    }
                }
                if (callback) {
                    console.log(resObj)
                    // alert(JSON.stringify(resObj))
                    callback(resObj);
                }
                console.log('JS received response:', responseData);
            });
        } else {
            setTimeout(() => {
                getBridge()
            }, 500)
        }
    }
    getBridge()
}

// 注册native调用h5方法
function registerHandler (actionName, callback) {
    if (inBBJ()) {
        window.bridge.registerHandler(actionName, function (data, responseCallback) {
            console.log('JS Echo called with:', data);
            if (callback) {
                if (typeof data == 'string') {
                    try {
                        let jsonData = JSON.parse(data);
                        if (jsonData) {
                            callback(jsonData);
                        } else {
                            callback(data);
                        }
                    } catch (e) {
                        console.log(e)
                        // Toast(e)
                        // alert(e)
                    }
                } else {
                    callback(data);
                }
            }
        });
    }
}

//订单信息埋点
let reportBranch = (obj) => {
    return new Promise((resolve, reject) => {
        try {
            if (inBBJ()) {
                callHandler('report_branch', obj, resolve)
            }
        }
        catch (e) {
            reject(e)
        }
    })
}


//跳转
let navigateTo = (obj, _vue, type) => {
    return new Promise((resolve, reject) => {
        try {
            if (inBBJ()) {
                let datas = {
                    url: window.location.origin + '/#/' + to.fullPath,
                    title: 'OTC',
                    needLogin: true,
                    popVC: to.query.replace == 1 ? true : false,     //跳转的时候是否干掉当前页面
                    hiddenNav: true,     //是否全屏
                }
                callHandler('openUrl', datas, resolve)
            } else {
                type === 'push' && _vue.$router.push(obj);
                type === 'replace' && _vue.$router.replace(obj);
            }
        } catch (e) {
            reject(e)
        }
    })
}

//返回
let navigateBack = (target, _vue, special) => {
    if (inBBJ()) {
        let datas = {};
        if (typeof target === 'string' && target.indexOf('http') > -1) datas.url = target
        if (typeof target === 'number') datas.index = target
        if (special && special === 'special2') datas.index = -2;
        callHandler('popUrl', datas)
    } else {
        if (typeof target === 'number') _vue.$router.go(target)
    }
}

//将科学计数法转变成正常用户可视格式
function toNonExponential (num) {
    if (typeof num === 'string') num = Number(num);
    var m = num.toExponential().match(/\d(?:\.(\d*))?e([+-]\d+)/);
    return num.toFixed(Math.max(0, (m[1] || '').length - m[2]));
}

//代币合约地址
let addressAbi = {
    USDT: '0xdAC17F958D2ee523a2206206994597C13D831ec7',
    DAI: '0x6b175474e89094c44da98b954eedeac495271d0f'
}

//汇率
let exchanges = {
    ETH: 1000000000000000000,
    DAI: 1000000000000000000,
    USDT: 1000000
}

//配置
// let abiArray = [{"constant":true,"inputs":[],"name":"mintingFinished","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"cap","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"unpause","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_amount","type":"uint256"}],"name":"mint","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_value","type":"uint256"}],"name":"burn","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"paused","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_subtractedValue","type":"uint256"}],"name":"decreaseApproval","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"balance","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"finishMinting","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"pause","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_addedValue","type":"uint256"}],"name":"increaseApproval","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"burner","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Burn","type":"event"},{"anonymous":false,"inputs":[],"name":"Pause","type":"event"},{"anonymous":false,"inputs":[],"name":"Unpause","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"amount","type":"uint256"}],"name":"Mint","type":"event"},{"anonymous":false,"inputs":[],"name":"MintFinished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"}];
let abiArray = [{ "constant": true, "inputs": [], "name": "name", "outputs": [{ "name": "", "type": "string" }], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": false, "inputs": [{ "name": "_spender", "type": "address" }, { "name": "_value", "type": "uint256" }], "name": "approve", "outputs": [{ "name": "", "type": "bool" }], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": true, "inputs": [], "name": "totalSupply", "outputs": [{ "name": "", "type": "uint256" }], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": false, "inputs": [{ "name": "_from", "type": "address" }, { "name": "_to", "type": "address" }, { "name": "_value", "type": "uint256" }], "name": "transferFrom", "outputs": [{ "name": "", "type": "bool" }], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": true, "inputs": [], "name": "decimals", "outputs": [{ "name": "", "type": "uint8" }], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [{ "name": "_owner", "type": "address" }], "name": "balanceOf", "outputs": [{ "name": "balance", "type": "uint256" }], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [], "name": "symbol", "outputs": [{ "name": "", "type": "string" }], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": false, "inputs": [{ "name": "_to", "type": "address" }, { "name": "_value", "type": "uint256" }], "name": "transfer", "outputs": [{ "name": "", "type": "bool" }], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": true, "inputs": [{ "name": "_owner", "type": "address" }, { "name": "_spender", "type": "address" }], "name": "allowance", "outputs": [{ "name": "", "type": "uint256" }], "payable": false, "stateMutability": "view", "type": "function" }, { "payable": true, "stateMutability": "payable", "type": "fallback" }, { "anonymous": false, "inputs": [{ "indexed": true, "name": "owner", "type": "address" }, { "indexed": true, "name": "spender", "type": "address" }, { "indexed": false, "name": "value", "type": "uint256" }], "name": "Approval", "type": "event" }, { "anonymous": false, "inputs": [{ "indexed": true, "name": "from", "type": "address" }, { "indexed": true, "name": "to", "type": "address" }, { "indexed": false, "name": "value", "type": "uint256" }], "name": "Transfer", "type": "event" }];

//读取一些基础配置
const siteConfig = token => {
    return new Promise((resolve, reject) => {
        fetch(`${ajaxUrl}/site/config`, {
            token: token || getToken()
        }).then(res => {
            if (res.retCode === 0) {
                resolve(res.retData)
            } else {
                reject('')
            }
        }).catch(error => {
            reject('')
            console.log(error)
        })
    })
}

//获取随机字符串 e 字符串长度
function randomString (e) {
    e = e || 32;
    var t = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678",
        a = t.length,
        n = "";
    for (let i = 0; i < e; i++) n += t.charAt(Math.floor(Math.random() * a));
    return n
}

//对象转URL参数
function objTransUrlParams (obj) {
    const params = [];
    Object.keys(obj).forEach((key) => {
        let value = obj[key]
        if (typeof value === 'undefined') {
            value = ''
        }
        params.push([key, value].join('='))
    })
    return params.join('&')
}

//对象asscii 排序
function sort_ASCII (obj) {
    var arr = new Array();
    var num = 0;
    for (var i in obj) {
        arr[num] = i;
        num++;
    }
    var sortArr = arr.sort();
    var sortObj = {};
    for (var i in sortArr) {
        sortObj[sortArr[i]] = obj[sortArr[i]];
    }
    return sortObj;
}


//获取签名信息
function getHashStr (strObj) {
    let appKey = {
        appid: 190219,
        appsecret: '5ca5087fd74a5afd5cb1cad3016e4980'
    }
    strObj['appid'] = appKey.appid
    strObj['randomstr'] = randomString(6)
    strObj['timestamp'] = new Date().getTime();
    strObj['convertPOST'] = 1;
    strObj = sort_ASCII(strObj)
    let queryStr = objTransUrlParams(strObj)
    let hash = CryptoJS.HmacSHA256(queryStr, appKey.appsecret).toString();
    return md5(hash).toLocaleLowerCase()
}

/**
 * @description 邮箱-*
 * @param email 要转换的邮箱
 */
function emailStar (email) {
    if (!email || !email.includes('@')) return ''
    let nArr = email.split('@')
    let n = nArr[0]
    n = n.slice(0, 3)
    return `${n}***@${nArr[1]}`
}

//检测用户实名认证状态
function checkRealName (token) {
    return new Promise(resolve => {
        fetch(`${ajaxUrl}/otc/otc-config`, {
            token: token
        }).then(res => {
            if (res.retCode === 0) {
                resolve(res.retData)
            }
            // resolve(res.retCode === 0?res.retData.kyc_status:0)
        })
    })
}

function checkDialog () {
    return new Promise(resolve => {
        resolve('')
    })
}

function formatBTC (btcData, coinType = 'BTC') {
    const num = Number(btcData);
    return num.toFixed(coinType === 'BTC' ? 8 : 2);
}

function getRedTypeDes (bstype) {
    const newType = parseInt(bstype);
    switch (newType) {
        case 3: return '的建仓包'; break;
        case 4: return '的平仓包'; break;
        case 5: return '的止盈包'; break;
        case 6: return '的止损包'; break;
        case 7: return '的爆仓包'; break;
        case 8: return '的结算包'; break;
        default: return '';
    }
}

/**
 * @description 将科学计数法转变成正常用户可视格式
 * @param num 需要转换的数值
 */
function toNonExponential2 (num_str) {
    if (!num_str) return '';
    if (typeof num_str === 'number') num_str = num_str.toString();
    if (num_str.indexOf("+") != -1) {
        num_str = num_str.replace("+", "");
    }
    if (num_str.indexOf("E") != -1 || num_str.indexOf("e") != -1) {
        let resValue = "",
            power = "",
            result = null,
            dotIndex = 0,
            resArr = [],
            sym = "";
        let numStr = num_str.toString();
        if (numStr[0] == "-") {
            // 如果为负数，转成正数处理，先去掉‘-’号，并保存‘-’.
            numStr = numStr.substr(1);
            sym = "-";
        }
        if (numStr.indexOf("E") != -1 || numStr.indexOf("e") != -1) {
            let regExp = new RegExp(
                "^(((\\d+.?\\d+)|(\\d+))[Ee]{1}((-(\\d+))|(\\d+)))$",
                "ig"
            );
            result = regExp.exec(numStr);
            if (result != null) {
                resValue = result[2];
                power = result[5];
                result = null;
            }
            if (!resValue && !power) {
                return false;
            }
            dotIndex = resValue.indexOf(".") == -1 ? 0 : resValue.indexOf(".");
            resValue = resValue.replace(".", "");
            resArr = resValue.split("");
            if (Number(power) >= 0) {
                let subres = resValue.substr(dotIndex);
                power = Number(power);
                //幂数大于小数点后面的数字位数时，后面加0
                for (let i = 0; i <= power - subres.length; i++) {
                    resArr.push("0");
                }
                resArr.push("0");
                if (power - subres.length < 0) {
                    resArr.splice(dotIndex + power, 0, ".");
                }
            } else {
                power = power.replace("-", "");
                power = Number(power);
                //幂数大于等于 小数点的index位置, 前面加0
                for (let i = 0; i < power - dotIndex; i++) {
                    resArr.unshift("0");
                }
                resArr.unshift("0");
                let n = power - dotIndex >= 0 ? 1 : -(power - dotIndex);
                resArr.splice(n, 0, ".");
            }
        }

        resValue = resArr.join("");
        return sym + resValue;
    } else {
        return num_str
    }
}

/**
 * 截取小数位数
 * @param target 需要截取的小数
 * @param len 需要截取的位数
 */
function intercept (target, len) {
    len = len || 8;
    if (!target || isNaN(Number(target))) return target;
    if (typeof target === 'number') target = target.toString();
    target = toNonExponential2(target);
    if (target.indexOf('.') > -1) {
        let arrTarget = target.split('.');
        if (arrTarget.length > 0 && arrTarget[1].length > len) {
            arrTarget[1] = arrTarget[1].substr(0, len);
        }
        return arrTarget.join('.');
    } else {
        return target
    }
}

//读取本地缓存中的语言配置
function readLang () {
    let lang = getCookie('lang') || 'zh';
    if (lang.indexOf('"') > -1) {
        lang = lang.replace('"', '');
        lang = lang.replace('"', '');
    }
    return lang
}

function checkVersion () {
    //返回数字格式
    let n = getVersion().split('.').join('');
    return Number(n)
}

//去除字符串前后空格
function trim (str) {
    return str.replace(/(^\s*)/g, "").replace(/(\s*$)/g, "");
}

//检测是否含有表情
function isEmojiCharacter (substring) {
    for (var i = 0; i < substring.length; i++) {
        var hs = substring.charCodeAt(i);
        if (0xd800 <= hs && hs <= 0xdbff) {
            if (substring.length > 1) {
                var ls = substring.charCodeAt(i + 1);
                var uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                if (0x1d000 <= uc && uc <= 0x1f77f) {
                    return true;
                }
            }
        } else if (substring.length > 1) {
            var ls = substring.charCodeAt(i + 1);
            if (ls == 0x20e3) {
                return true;
            }
        } else {
            if (0x2100 <= hs && hs <= 0x27ff) {
                return true;
            } else if (0x2B05 <= hs && hs <= 0x2b07) {
                return true;
            } else if (0x2934 <= hs && hs <= 0x2935) {
                return true;
            } else if (0x3297 <= hs && hs <= 0x3299) {
                return true;
            } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030
                || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b
                || hs == 0x2b50) {
                return true;
            }
        }
    }
}

export default {
    isEmojiCharacter,
    trim,
    readLang,
    status,
    getRedTypeDes,
    formatBTC,
    checkDialog,
    ajaxUrl,
    ajaxUrl2,
    ajaxUrl3,
    ajaxUrl4,
    wssUrl,
    getQueryString,
    client,
    accAdd,
    subtr,
    accMul,
    accDiv,
    getToken,
    fetch,
    fetch2,
    setStorage,
    setStorage2,
    getStorage,
    getStorage2,
    time,
    bridgeData,
    transTime,
    inBBJ,
    callHandler,
    registerHandler,
    navigateBack,
    waitSDKReady,
    getPriceByName,
    countNum,
    isIphoneX,
    debug,
    transTime2,
    transTime3,
    transTime4,
    transTime5,
    abiArray,
    addressAbi,
    exchanges,
    toNonExponential,
    toNonExponential2,
    intercept,
    siteConfig,
    setCookie,
    getCookie,
    delCookie,
    checkRealName,
    getCurrencyRate,
    Nigeria,
    randomString,
    getHashStr,
    emailStar,
    reportBranch,
    getVersion,
    checkVersion
}